<template>
  <div class="customer-contracts-container">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>我的合同</h2>
        <!-- 返回主页按钮 -->
        <button @click="goToDashboard" class="btn btn-back">
          <i class="fa fa-home mr-2"></i>返回主页
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载合同中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <!-- 合同列表 -->
    <div v-if="!loading && contracts.length > 0" class="card mt-4">
      <div class="card-body">
        <div class="contracts-table overflow-x-auto">
          <table class="table table-bordered table-hover">
            <thead class="bg-light">
            <tr>
              <th>合同ID</th>
              <th>合同名称</th>
              <th>创建时间</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="contract in contracts" :key="contract.id">
              <td>{{ contract.id }}</td>
              <td>{{ contract.name }}</td>
              <td>{{ formatDate(contract.createTime) }}</td>
              <td><span :class="getStatusClass(contract.status)">{{ getStatusText(contract.status) }}</span></td>
              <td>
                <button @click="viewContract(contract.id)" class="btn btn-view">
                  <i class="fa fa-eye mr-2"></i>查看详情
                </button>
              </td>
            </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页控件 -->
        <div class="pagination mt-3 d-flex justify-content-between flex-wrap gap-2">
          <div>
            每页显示 {{ pageSize }} 条，共 {{ totalItems }} 条
          </div>
          <div class="pagination-controls d-flex align-items-center gap-3">
            <!-- 分页按钮 -->
            <div class="pagination-buttons d-flex align-items-center">
              <button
                  @click="prevPage"
                  :disabled="currentPage === 0"
                  class="btn btn-page"
                  title="上一页"
              >
                <i class="fa fa-chevron-left"></i> 上一页
              </button>
              <span class="page-info mx-2">
                第 {{ currentPage + 1 }} 页，共 {{ totalPages }} 页
              </span>
              <button
                  @click="nextPage"
                  :disabled="currentPage === totalPages - 1"
                  class="btn btn-page"
                  title="下一页"
              >
                下一页 <i class="fa fa-chevron-right"></i>
              </button>
            </div>

            <!-- 跳转页面控件 -->
            <div class="page-jump d-flex align-items-center gap-2">
              <span>跳至：</span>
              <input
                  type="number"
                  v-model.number="jumpPageNum"
                  :min="1"
                  :max="totalPages"
                  class="form-control page-input"
                  @keyup.enter="handleJump"
                  placeholder="页码"
                  title="输入页码后按回车或点击确认"
              >
              <button
                  @click="handleJump"
                  :disabled="!isJumpValid"
                  class="btn btn-jump"
                  title="确认跳转"
              >
                <i class="fa fa-arrow-right mr-1"></i>确认
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 无合同提示 -->
    <div v-else-if="!loading && contracts.length === 0" class="card mt-4">
      <div class="card-body">
        <div class="empty-message text-center py-4">
          <i class="fa fa-file-contract text-muted display-4 mb-3"></i>
          <h4>暂无相关合同</h4>
          <p class="text-muted">您还没有相关的合同记录</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted, watch, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default {
  name: 'CustomerContracts',
  setup() {
    const store = useStore()
    const router = useRouter()

    // 基础数据
    const loading = ref(true)
    const errorMessage = ref('')
    const contracts = ref([])
    const currentPage = ref(0)
    const pageSize = ref(10)
    const totalPages = ref(1)
    const totalItems = ref(0)
    const customerId = ref(null)

    // 跳转页面相关
    const jumpPageNum = ref(1)

    // 合同状态映射
    const CONTRACT_STATUS = {
      DRAFT: { text: '草稿', class: 'status-draft' },
      PENDING_REVIEW: { text: '待审核', class: 'status-pending-review' },
      REVIEW_FAILED: { text: '审核失败', class: 'status-review-failed' },
      PENDING_CONFIRMATION: { text: '待确认', class: 'status-pending-confirmation' },
      CONFIRMED: { text: '已确认', class: 'status-confirmed' },
      COMPLETED: { text: '已完成', class: 'status-completed' },
      ARCHIVED: { text: '已归档', class: 'status-archived' }
    }

    // 判断跳转页码是否有效
    const isJumpValid = computed(() => {
      return Number.isInteger(jumpPageNum.value) &&
          jumpPageNum.value >= 1 &&
          jumpPageNum.value <= totalPages.value &&
          jumpPageNum.value !== currentPage.value + 1
    })

    // 返回主页
    const goToDashboard = () => {
      router.push('/customer/home')
    }

    // 获取合同数据
    const fetchCustomerContracts = () => {
      loading.value = true
      errorMessage.value = ''

      if (!customerId.value) {
        errorMessage.value = '用户信息加载中，请稍后...'
        loading.value = false
        return
      }

      axios.get(`/auth/contracts/customer/${customerId.value}`, {
        params: {
          page: currentPage.value,
          size: pageSize.value
        }
      })
          .then(response => {
            contracts.value = response.data.content || []
            totalItems.value = response.data.totalElements || 0
            totalPages.value = response.data.totalPages || 1
            jumpPageNum.value = currentPage.value + 1
          })
          .catch(error => {
            console.error('获取合同失败', error)
            errorMessage.value = error.response?.data?.message || '获取合同失败，请稍后再试'
          })
          .finally(() => {
            loading.value = false
          })
    }

    // 查看合同详情
    const viewContract = (contractId) => {
      router.push(`/contracts/${contractId}/detail2`)
    }

    // 分页操作
    const prevPage = () => {
      if (currentPage.value > 0) {
        currentPage.value--
        fetchCustomerContracts()
      }
    }

    const nextPage = () => {
      if (currentPage.value < totalPages.value - 1) {
        currentPage.value++
        fetchCustomerContracts()
      }
    }

    // 处理跳转页面
    const handleJump = () => {
      if (!isJumpValid.value) return

      currentPage.value = jumpPageNum.value - 1
      fetchCustomerContracts()
    }

    // 日期格式化
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString()
    }

    // 获取状态文本
    const getStatusText = (status) => {
      return CONTRACT_STATUS[status]?.text || status
    }

    // 获取状态样式
    const getStatusClass = (status) => {
      return CONTRACT_STATUS[status]?.class || 'status-unknown'
    }

    // 初始化
    onMounted(() => {
      customerId.value = store.state.user?.id

      watch(
          () => store.state.user?.id,
          () => {
            customerId.value = store.state.user?.id
            fetchCustomerContracts()
          }
      )

      fetchCustomerContracts()
    })

    return {
      loading,
      errorMessage,
      contracts,
      currentPage,
      pageSize,
      totalPages,
      totalItems,
      jumpPageNum,
      isJumpValid,
      goToDashboard,
      viewContract,
      prevPage,
      nextPage,
      handleJump,
      formatDate,
      getStatusText,
      getStatusClass
    }
  }
}
</script>

<style scoped>
.customer-contracts-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  background-color: #f8f9fa;
  padding: 15px 20px;
  border-radius: 6px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 基础按钮样式 */
.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.btn i {
  font-size: 14px;
}

.btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 按钮分类样式 */
.btn-back {
  background-color: #6c757d;
  color: #fff;
}

.btn-back:hover {
  background-color: #5a6268;
}

.btn-view {
  background-color: #007bff;
  color: #fff;
}

.btn-view:hover {
  background-color: #0069d9;
}

.btn-page {
  background-color: #f8f9fa;
  color: #495057;
  border: 1px solid #dee2e6;
  padding: 4px 10px;
}

.btn-page:hover {
  background-color: #e9ecef;
}

.btn-jump {
  background-color: #28a745;
  color: #fff;
}

.btn-jump:hover {
  background-color: #218838;
}

.btn-jump:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

/* 加载状态 */
.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  min-height: 300px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border-top-color: #0d6efd;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 错误消息 */
.error-message {
  color: #dc3545;
  background-color: #f8d7da;
  padding: 12px 15px;
  border-radius: 4px;
  margin: 10px 0;
  display: flex;
  align-items: center;
  border-left: 3px solid #dc3545;
}

/* 卡片样式 */
.card {
  border: none;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  margin-bottom: 20px;
}

.card-body {
  padding: 20px;
}

/* 表格样式 */
.table {
  width: 100%;
  margin-bottom: 0;
  border-collapse: separate;
  border-spacing: 0;
}

.table th,
.table td {
  padding: 0.75rem;
  vertical-align: middle;
  border-bottom: 1px solid #e5e7eb;
}

.table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #495057;
  border-bottom: 2px solid #e9ecef;
}

.table tr:hover {
  background-color: #f8fafc;
  transition: background-color 0.2s;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.pagination-controls {
  display: flex;
  align-items: center;
}

.page-info {
  color: #495057;
  font-size: 14px;
}

/* 跳转页面控件样式 */
.page-jump {
  margin-left: 15px;
  padding-left: 15px;
  border-left: 1px solid #e9ecef;
}

.page-input {
  width: 60px;
  padding: 4px 8px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  text-align: center;
}

.page-input:focus {
  outline: none;
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

/* 空状态样式 */
.empty-message {
  text-align: center;
  padding: 40px 20px;
  background-color: #f8fafc;
  border-radius: 6px;
  border: 1px dashed #e2e8f0;
}

.empty-message i {
  color: #94a3b8;
  margin-bottom: 15px;
}

.empty-message h4 {
  color: #1e293b;
  margin-bottom: 8px;
}

.empty-message p {
  color: #64748b;
  margin: 0;
}

/* 合同状态样式 */
.status-draft {
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #f8f9fa;
  color: #6c757d;
}

.status-pending-review {
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #fff3cd;
  color: #856404;
}

.status-review-failed {
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #f8d7da;
  color: #721c24;
}

.status-pending-confirmation {
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #cce5ff;
  color: #004085;
}

.status-confirmed {
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #d4edda;
  color: #155724;
}

.status-completed {
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #c3e6cb;
  color: #155724;
}

.status-archived {
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #e2e3e5;
  color: #383d41;
}

.status-unknown {
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #f8f9fa;
  color: #6c757d;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .pagination {
    flex-direction: column;
    align-items: flex-start !important;
  }

  .pagination-controls {
    width: 100%;
    justify-content: space-between;
    margin-top: 10px;
  }

  .page-jump {
    margin-left: 0;
    padding-left: 0;
    border-left: none;
  }
}
</style>
